package cn.itsource.pet.service.impl;

import cn.itsource.basic.exception.CustomException;
import cn.itsource.basic.utils.*;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.domain.User;
import cn.itsource.org.domain.dto.AcceptDto;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.mapper.UserMapper;
import cn.itsource.pet.domain.*;
import cn.itsource.pet.mapper.OrderPetAcquisitionMapper;
import cn.itsource.pet.mapper.PetMapper;
import cn.itsource.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.itsource.pet.mapper.SearchMasterMsgMapper;
import cn.itsource.pet.service.ISearchMasterMsgService;
import cn.itsource.basic.base.service.impl.BaseServiceImpl;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author huang
 * @since 2022-07-22
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;

    @Override
    public void publish(SearchMasterMsg msg) {
        //设置寻主消息为待审核状态
        msg.setState(0);
        //寻主消息入库
        searchMasterMsgMapper.insert(msg);
        //查询发布消息的用户
        User user = userMapper.loadById(msg.getUserId());
        //百度ai审核
        if (!BaiduAuditUtils.TextCensor(msg.getTitle() + msg.getName() +
                msg.getCoatColor() + msg.getAddress())) {
            //审核不通过，不抛异常，发短信给用户提示，保存日志，改变寻主消息状态
//            SmsUtil.sendSms(user.getPhone(),"您发布的消息疑似存在敏感信息，请确认后重试！");
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setAuditTime(new Date());
            log.setNote("发布消息中存在敏感信息！");
            //保存审核失败日志
            searchMasterMsgAuditLogMapper.insert(log);
            msg.setState(-1);
        } else {
            //审核通过,改变审核状态
            msg.setState(1);
            msg.setNote("审核通过！happy得很！");
//            SmsUtil.sendSms(user.getPhone(),"您发布的消息已审核通过，请静候佳音！");
            //获取当前寻主信息地址坐标
            Point point = DistanceUtil.getPoint(msg.getAddress());
            //查询离当前填写地址50km最近的店铺
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());
            if (nearestShop != null) {
                //如果存在改变寻主消息的shopID
                msg.setShopId(nearestShop.getId());
            }
            //如果不存在，就什么也不操作（寻主池）
        }
        searchMasterMsgMapper.update(msg);
    }

    @Override
    public void accept(AcceptDto dto) {
        //判断是否已经存在待处理订单
        OrderPetAcquisition op = orderPetAcquisitionMapper.selectToHandleOrderByMsgId(dto.getMsgId());
        //如果有则返回自定义异常
        if (op != null) {
            throw new CustomException("已存在待处理收购单！！");
        }
        //根据寻主消息生成宠物基本信息
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(dto.getMsgId());
        Pet pet = initMsg2Pet(msg, dto.getHandler());
        //保存宠物
        petMapper.insert(pet);
        //ctrl+alt+m，单独抽方法,保存收购单
        orderPetAcquisitionMapper.insert(initAcquisition(dto, msg, pet));
    }

    private OrderPetAcquisition initAcquisition(AcceptDto dto, SearchMasterMsg msg, Pet pet) {
        OrderPetAcquisition opa = new OrderPetAcquisition();
        opa.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getMsgId()));
        opa.setDigest(pet.getName()+"收狗计划");
        opa.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        opa.setState(0);
        opa.setPetId(pet.getId());
        opa.setUserId(msg.getUserId());
        opa.setShopId(dto.getHandler().getShopId());
        opa.setAddress(msg.getAddress());
        opa.setEmpId(dto.getHandler().getId());
        opa.setSearchMasterMsgId(msg.getId());
        return opa;
    }

    private Pet initMsg2Pet(SearchMasterMsg msg, Employee emp) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setState(0L);
        pet.setTypeId(msg.getPetType());
        pet.setCreatetime(new Date());
        pet.setShopId(emp.getShopId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
